package me.jiatao.baselibrary.ui.fragment

import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnLoadMoreListener
import me.jiatao.baselibrary.R
import me.jiatao.baselibrary.mvp.presenter.BasePresenter
import me.jiatao.baselibrary.mvp.view.BaseView
import me.jiatao.baselibrary.utils.NetWorkUtil
import me.jiatao.baselibrary.widgets.decoration.SpaceItemDecoration

/**
 * @author chenxz
 * @date 2019/11/17
 * @desc BaseMvpListFragment
 */
abstract class BaseMvpListFragment<V : BaseView, P : BasePresenter<V>> : BaseMvpFragment<V, P>() {

    /**
     * SwipeRefreshLayout对象
     */
    protected var swipeRefreshLayout: SwipeRefreshLayout? = null

    /**
     * RecyclerView对象
     */
    protected var recyclerView: RecyclerView? = null

    /**
     * 是否是下拉刷新
     */
    protected var isRefresh = false

    /**
     * LoadMoreListener
     */
    protected val onRequestLoadMoreListener by lazy {
        OnLoadMoreListener {
            isRefresh = false
            swipeRefreshLayout?.isRefreshing = false
            onLoadMoreList()
        }
    }

    override fun initView(view: View) {
        super.initView(view)

        /**
         * 初始化SwipeRefreshLayout
         */
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout)
        swipeRefreshLayout?.setOnRefreshListener {
            isRefresh = true
            onRefreshList()
        }

        /**
         * 初始化 RecyclerView
         */
        recyclerView = view.findViewById(R.id.recycler_view)
        recyclerView?.run {
            layoutManager = LinearLayoutManager(mActivity)
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(mActivity))
        }
    }


    override fun showLoading() {

    }

    override fun hideLoading() {
        if (isRefresh) {
            swipeRefreshLayout?.isRefreshing = false
        }
    }

    override fun onError(errorMsg: String) {
        if (isRefresh) {
            swipeRefreshLayout?.isRefreshing = false
        }

    }


    /**
     * 下拉刷新
     */
    abstract fun onRefreshList()

    /**
     * 上拉加载更多
     */
    abstract fun onLoadMoreList()
}